package com.heima.article.service.iml;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.heima.common.exception.CustException;
import com.heima.feigins.AdminFeign;
import com.heima.feigins.ArticleFeigin;
import com.heima.feigins.WemediaFigin;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    WemediaFigin wemediaFigin;

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    ArticleFeigin articleFeigin;

    @Autowired
    AuthorMapper authorMapper;
    /*
    * 发布文章信息
    * */
    @Override
    public void publishNews(Integer newsId) {
      //1.校验参数
        if (newsId ==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数文章id为空");
        }
      //2.根据id查询文章信息，并判断文章的状态，只有状态为4或8，才能进行发布文章
        WmNews wmNews = getNews(newsId);
      //3.封装ap_article，封装频道信息和作者信息
        ApArticle apArticle = getApArticle(wmNews);
        //封装好，进行保存或修改
        saveOrUpdateArticle(apArticle);
      //5. 保存信息到ap_config,ap_content
        saveConfigAndContent(wmNews,apArticle);
      //6.TODO 页面静态化---后边做
        //8.更新文章状态信息,改为9
        updateWmNews(newsId,wmNews,apArticle);
        //9.TODO 添加到es搜索--后边做
    }

    //更新文章状态信息,改为8
    private void updateWmNews(Integer newsId, WmNews wmNews, ApArticle apArticle) {
        wmNews.setStatus((short) 9);
        wmNews.setArticleId(apArticle.getId());
        ResponseResult<WmNews> result = wemediaFigin.updateWmNews(wmNews);
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用修改文章接口失败");
        }
    }

    //保存信息到ap_config,ap_content
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        articleConfigMapper.insert(apArticleConfig);

        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);
    }

    @Autowired
    ApArticleConfigMapper articleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    //保存或修改文章数据,apArticle是自媒体人创建的
    private void saveOrUpdateArticle(ApArticle apArticle) {
        //判断文章aparticle是否被之前的WmNews关联。
        if (apArticle.getId()==null){
            //apArticle没有创建过
            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            this.save(apArticle);
        }else {//有关联，就是要修啊该apArticle
            // 修改文章  删除之前关联的配置信息   内容信息
            ApArticle byId = this.getById(apArticle.getId());
            if (byId==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"自媒体创建的关联的文章不存在");
            }
            this.updateById(apArticle);
            //查询配置表的信息，删除掉
            articleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,apArticle.getId()));
            //content的信息，删除掉
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
        }
    }

    //封装ap_article，
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        //将属性字段相同的进行复制
        BeanUtils.copyProperties(wmNews,apArticle);
        //不相同的字段手动进行映射
        apArticle.setId(wmNews.getArticleId());
        apArticle.setLayout(wmNews.getType());
        apArticle.setFlag((byte) 0);
        //频道信息
        ResponseResult<AdChannel> one = adminFeign.findOne(wmNews.getChannelId());
        if (!one.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"adminFigin远程调用出错了");
        }
        AdChannel data = one.getData();
        if (data ==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"频道信息不存在");
        }
        apArticle.setChannelName(data.getName());
       //作者名称
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getUserId, wmNews.getUserId()));
         if (apAuthor == null){
             CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"作者信息不存在");
         }
         apArticle.setAuthorName(apAuthor.getName());
         apArticle.setAuthorId(apAuthor.getId().longValue());

        return apArticle;

    }

    //根据自媒体文章id查询文章信息
    private WmNews getNews(Integer newsId) {
        ResponseResult<WmNews> news = wemediaFigin.findNewsById(newsId);

        if (!news.checkCode()){
          CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"wemediaFigin远程调用出错了");
        }
        //取出数据
        WmNews data = news.getData();
        if (data ==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章信息不存在");
        }
        //判断文章状态是否为4或8，是方能发布文章
        if (!data.getStatus().equals(WemediaConstants.WM_NEWS_AUTH_PASS) && !data.getStatus().equals(WemediaConstants.WM_NEWS_AUTHED_STATUS)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章状态既不是人工审核通过的4也不是自动审核通过的8");
        }
        return data;
    }
}